#include<iostream>
#include<pthread.h>
#include<unistd.h>
#include<string>

pthread_cond_t Cond=PTHREAD_COND_INITIALIZER;

pthread_mutex_t Mutex=PTHREAD_MUTEX_INITIALIZER;

int tickets=1000;

void *ThreadRoutine(void*args)
{
    std::string threadname=static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&Mutex);
        if(tickets)
        {
            std::cout<<threadname<<"get a ticket "<<tickets--<<std::endl;
            usleep(1000);
        }
        else
        {
            printf("%s\n","no tickets");
            pthread_cond_wait(&Cond,&Mutex);
        }
        pthread_mutex_unlock(&Mutex);
    }

}
int main()
{
    pthread_t t1,t2,t3;
    pthread_create(&t1,nullptr,ThreadRoutine,(void*)"Thread-1");
    pthread_create(&t2,nullptr,ThreadRoutine,(void*)"Thread-2");
    pthread_create(&t3,nullptr,ThreadRoutine,(void*)"Thread-3");
    while(true)
    {
        sleep(6);
        pthread_mutex_lock(&Mutex);
        tickets+=1000;
        pthread_mutex_unlock(&Mutex);
        pthread_cond_signal(&Cond);
    }
    pthread_join(t1,nullptr);
    pthread_join(t2,nullptr);
    pthread_join(t3,nullptr);;
    return 0;

}